package com.yan.utils;

import com.alibaba.fastjson.JSONObject;
import com.yan.common.exception.HttpException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * Created by yanl_ on 2018/4/11.
 */
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 此处的key放在这种是为了放置Basic Auth
     */
    public static String getResponseContent(String url, String key, String requestBody) throws Exception {
        logger.info("request url:{} requestBody:{}", url, requestBody);
        URL requestUrl;
        // PrintWriter writer = null;
        OutputStream out = null;
        InputStream in = null;
        int code = 0;
        try {
            String basicContent = Base64.getEncoder().encodeToString((key + ":").getBytes("UTF-8"));
            String authorization = String.format("Basic %s", basicContent);

            requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", authorization);

            boolean flag = StringUtils.isEmpty(requestBody);

            if (!flag) {
                connection.setDoOutput(true);
                connection.setDoInput(true);     // 设置是否从httpUrlConnection读入，默认情况下是true;
//                writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
//                writer.write(requestBody);
//                writer.flush();
                IOUtils.write(requestBody, connection.getOutputStream(), "utf-8");

            } else {
                connection.setDoInput(true);     // 设置是否从httpUrlConnection读入，默认情况下是true;
            }

            connection.setConnectTimeout(30 * 1000); // 设置一个指定的超时值（以毫秒为单位）
            connection.setReadTimeout(60 * 1000);// 将读超时设置为指定的超时，以毫秒为单位。

            code = connection.getResponseCode();
            String content;
            if (code >= HttpURLConnection.HTTP_OK && code < HttpURLConnection.HTTP_MULT_CHOICE) {
                in = connection.getInputStream();
                content = IOUtils.toString(in, Charset.forName("UTF-8"));
                return content;
            } else {
                String errorMsg = connection.getResponseMessage();
                in = connection.getErrorStream();
                content = IOUtils.toString(in, Charset.forName("UTF-8"));
                logger.info("request url:{} errorInfo:{}", url, content);
                // throw new Exception(String.format("request url failed: %s , status:%d, msg:%s", url, code, errorMsg));
                throw new HttpException(code, connection.getResponseMessage(), content);
            }

        } catch (Exception e) {
            logger.error("request url:{},param:{},statusCode:{},errorMsg:{}", url, requestBody, code, e.getMessage());
            throw e;
        } finally {
            IOUtils.closeQuietly(out);
        }

    }


}
